package cn.xinfei.xdecision.common.utils.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

@Slf4j
public class HttpClient {

    private String charset;
    private String reqUrl;
    private int connectTimeout;
    private int readTimeOut;

    public HttpClient(String reqUrl, String charset, int connectTimeout, int readTimeOut) {
        this.setCharset(charset);
        this.setReqUrl(reqUrl);
        this.connectTimeout = connectTimeout;
        this.readTimeOut = readTimeOut;
    }

    public HttpClient(String reqUrl) {
        this.setCharset("UTF-8");
        this.setReqUrl(reqUrl);
        this.connectTimeout = 10000;
        this.readTimeOut = 10000;
    }

    public String post(Map<String, String> parameters) {
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        try {
            // 创建连接
            URL url = new URL(reqUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeOut);
            connection.connect();
            // POST请求
            out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(getRequestParamString(parameters, "UTF-8"));
            out.flush();
            out.close();
            int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("网络调用异常,code:" + responseCode + " ,msg: " + connection.getResponseMessage());
            }

            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(charset), charset);
                sb.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
            System.out.println("返回报文=" + sb.toString());
            return sb.toString();
        } catch (Exception e) {
            log.error("post error for parameters={}", JsonUtil.toJson(parameters), e);
            throw new RuntimeException("网络调用异常" + " : " + "，reqUrl=" + reqUrl + ",params=" + parameters);
        } finally {
            try {
                if (connection != null) {
                    connection.disconnect();
                }
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    private String getRequestParamString(Map<String, String> requestParam, String coder) {
        if (null == coder || "".equals(coder)) {
            coder = "UTF-8";
        }
        StringBuffer sf = new StringBuffer("");
        String reqstr = "";
        if (null != requestParam && 0 != requestParam.size()) {
            for (Entry<String, String> en : requestParam.entrySet()) {
                try {
                    sf.append(en.getKey()
                            + "="
                            + (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
                            .encode(en.getValue(), coder)) + "&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return "";
                }
            }
            reqstr = sf.substring(0, sf.length() - 1);
        }
        System.out.println(reqstr);
        return reqstr;
    }


    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public String getReqUrl() {
        return reqUrl;
    }

    public void setReqUrl(String reqUrl) {
        this.reqUrl = reqUrl;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public int getReadTimeOut() {
        return readTimeOut;
    }

    public void setReadTimeOut(int readTimeOut) {
        this.readTimeOut = readTimeOut;
    }

    public static void main(String[] args) {
        HttpClient smsClient = new HttpClient("http://test2-service.shoufuyou.com/sms/monitor", "UTF-8", 10000, 10000);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("mobiles", "18501625950");
        params.put("message", "测试");
        smsClient.post(params);
    }

}

